package com.example.chatroom.common;

import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;

// todo:密码加盐处理
public class PasswordTools {
    // todo: 密码加盐
    public static String encrypt(String password){
        // salt 盐值 32位
        String salt = UUID.randomUUID().toString().replace("-","");
        // salt 盐值和 password 明文密码 经 MD5 加密后的 saltPassword
        String saltPassword = DigestUtils.md5DigestAsHex((salt + password).getBytes());
        // finalPassword 最终密码，由salt盐值和saltPassword加盐后的密码拼接而成
        String finalPassword = salt + "$" + saltPassword;
        return finalPassword;
    }

    public static String encrypt(String password, String salt){
        String saltPassword = DigestUtils.md5DigestAsHex((salt+password).getBytes());
        String finalPassword = salt + "$" + saltPassword;
        return finalPassword;
    }

    // todo: 密码解密：验证密码正确性
    public static boolean decrypt(String password, String dbPassword){
        Boolean result = false;
        if(StringUtils.hasLength(password) || StringUtils.hasLength(dbPassword)
                || dbPassword.length() == 65){
            String salt = dbPassword.split("\\$")[0];
            String saltPassword = dbPassword.split("\\$")[1];
            String checkPassword = encrypt(password,salt);
            if(checkPassword.equals(dbPassword)){
                result = true;
            }
        }
        return result;
    }

    public static void main1(String[] args) {
        String password = "1234";
        String finalPassword = encrypt(password);
        System.out.println(finalPassword);

        Boolean ret = decrypt("123",finalPassword);
        System.out.println(ret);

        Boolean ret1 = decrypt("1234",finalPassword);
        System.out.println(ret1);
    }
}
